package com.suxin.thread.schedulev3.executor;

import com.suxin.thread.schedulev3.task.Task;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Tang
 * @classname MasterExecutor
 * @description [  ]
 * @date 2021/6/11 16:46
 */
public class MasterExecutor implements Runnable {

    private static ThreadPoolExecutor poolExecutor = null;

    private static LinkedBlockingQueue<Task> blockingQueue = new LinkedBlockingQueue<>(30);

    static {
        poolExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
                Runtime.getRuntime().availableProcessors() + 1,
                500, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(30),
                new CustomizableThreadFactory("MasterExecutor-"));
    }

    @Override
    public void run() {
        while (true) {
            Task task = null;
            try {
                task = blockingQueue.poll(500, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            if (task != null) {
                poolExecutor.execute(this::exec);
            }
        }
    }

    public void exec() {

    }

    public static void addTask(Task task) {
        blockingQueue.add(task);
    }

}